package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    //统计指定时间内的营业额数据
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();//当前集合用于存放从begin到end范围内每天的日期
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);//计算指定日期后一天对应的日期
            dateList.add(begin);
        }
        List<Double> turnoverList = new ArrayList<>();//存放每天的营业额
        for (LocalDate date : dateList){
            //LocalDateTime里面还包含时分秒  所以要算出这个日期的最早时间和最晚时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = (turnover == null )? 0.0 : turnover; //营业额为null则设置为0
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();//当前集合用于存放从begin到end范围内每天的日期
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);//计算指定日期后一天对应的日期
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>();//存放每天的新增用户数量 select count(id) from user where create_time > begin and create_time < end
        List<Integer> totalUserList = new ArrayList<>();//存放每天的用户总数 select count(id) from user where create_time < end
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();

            map.put("end", endTime);
            Integer totalUser = userMapper.countByMap(map);//统计总用户数(先构造map只put一个进去)

            map.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(map);//统计新用户数

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }
    //统计时间内的订单区间数据
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();//当前集合用于存放从begin到end范围内每天的日期
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);//计算指定日期后一天对应的日期
            dateList.add(begin);
        }
        //存放每天的订单总数 select count(id) from orders where order_time > begin and order_time < end
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天的有效订单数 select count(id) from orders where order_time > begin and order_time < end and pay_status = 5
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的订单总数
            Integer totalDayOrder = getOrderCount(beginTime, endTime, null);
            orderCountList.add(totalDayOrder);
            //查询每天的有效订单数
            Integer validDayOrder = getOrderCount(beginTime, endTime,Orders.COMPLETED);
            validOrderCountList.add(validDayOrder);
        }
        //查询订单总数
        Integer totalOrder = orderCountList.stream().reduce(Integer::sum).get();//方法引用
        //查询有效订单总数
        Integer validOrder = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate =0.0;
        if(totalOrder != 0){
            orderCompletionRate = validOrder.doubleValue() / totalOrder;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrder)
                .validOrderCount(validOrder)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status){//根据条件统计订单数量
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        log.info("查询订单数量，参数: {}", map);
        Integer result = orderMapper.countByMap(map);
        log.info("查询结果: {}", result);
        return result;
    }
    //销量排名top10
    //查order表里面订单status=5(已完成)，order_detail表里面根据number计算每个食物有多少份
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        //相当于获取goodsSalesDTO.getName()，再转化成list
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }
    @Override
    //导出运营数据报表
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据库，获取营业数据（最近30天）
        LocalDate dateBegin= LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        //通过POI将数据写到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据：时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            XSSFRow row = sheet.getRow(3);//获取第4行
            row.getCell(2).setCellValue(businessData.getTurnover());//营业额
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());//订单完成率
            row.getCell(6).setCellValue(businessData.getNewUsers());//新增用户数
            row = sheet.getRow(4);//获取第5行
            row.getCell(2).setCellValue(businessData.getValidOrderCount());//有效订单数
            row.getCell(4).setCellValue(businessData.getUnitPrice());//平均客单价
            //填充明细数据
            for(int i = 0; i < 30; i++){
                LocalDate date = dateBegin.plusDays(i);
                LocalDateTime begin = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO data = workspaceService.getBusinessData(begin, end);//获取指定日期的营业数据
                row =sheet.getRow(7 + i);//获取某一行
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(data.getTurnover());//营业额
                row.getCell(3).setCellValue(data.getValidOrderCount());//有效订单数
                row.getCell(4).setCellValue(data.getOrderCompletionRate());//订单完成率
                row.getCell(5).setCellValue(data.getUnitPrice());//平均客单价
                row.getCell(6).setCellValue(data.getNewUsers());//新增用户数
            }
            //通过输出流将Excel文件下载到客户端浏览器
            OutputStream out = response.getOutputStream();//获取输出流对象
            excel.write(out);
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
